#include "inc/my_include.h"
#include "inc/serial.h"
#include <termios.h>
#include <sys/ioctl.h>
#include "inc/gpio.h"

void ExitExe(int i);

int fd = 0;
int main(int argc, char *argv[])
{
	signal(SIGINT, ExitExe); //接收ctrl-c信号，主要是调试用

	char sPort[] = "/dev/ttyS2";
	fd = open(sPort, O_RDWR,1);
	if (fd < 0)
	{
		printf("OpenSPort open %s error! %d\n", sPort, fd);
		return -1;
	}
	int baudRate = 9600;
	if( set_speed( fd, baudRate ) < 0 )
	{
		printf( "set_speed error!\n" );
		return -1;
	}

	int dataBits = 8, stopBits = 1, parity = 'n';
	if( set_other_attribute( fd, dataBits, stopBits, parity, 0, 20 ) < 0 )
	{
		printf( "set_other_attribute error!\n" );
		return -1;
	}

	printf( "%s:%d,%c,%d,%d\n", sPort, baudRate, parity, dataBits, stopBits );

	int pio = open(DEV_PIO, O_RDWR);
	if (pio < 0) {
		printf("open PIO device error! %d", pio);
		return -1;
	}
//	set_gpio();
	gpio_out( pio, AT91_PIN_PC11, 0 );
//	gpio_out( pio, AT91_PIN_PC11, 1 );
/*	int ctrlbits;
	ioctl(fd, TIOCMGET, &ctrlbits) ;
    ctrlbits |= TIOCM_RTS;
//	ctrlbits &= ~TIOCM_RTS;
	ioctl(fd, TIOCMSET, &ctrlbits);
	printf( "%x\n", ctrlbits );*/

	int i = 0;
	char smsg[256];
	for( i = 0; i < sizeof(smsg); ++i )
		smsg[i] = 0x55;
	while ( 1 )
	{
		int retS = read(fd, smsg, sizeof(smsg)-2);
		if (retS > 0)
		{
			gpio_out( pio, AT91_PIN_PC11, 1 );
			int retR = write(fd, smsg, retS);
			if (retR < retS)
			{
				printf("serial_thread write error!\n");
			}
			smsg[retS] = '\n';
			smsg[retS+1] = 0;
			printf( smsg );
		}else{
			printf( "timeout,retS:%d bytes\n", retS );
		}
	}

	return 0;
}

//接收ctrl-c信号，主要是调试用
void ExitExe(int i)
{
	if( fd )
		close(fd);
	exit(0);
}
